package com.habdqn.easybuy.web.manage.news;

import com.habdqn.easybuy.entity.News;
import com.habdqn.easybuy.entity.User;
import com.habdqn.easybuy.service.NewsService;
import com.habdqn.easybuy.service.impl.NewsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @author Xing.Jiejian
 * @date 2020/11/28
 */
@WebServlet(name = "NewsAddServlet", urlPatterns = "/manage/news/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        News news = new News();
        news.setTitle(request.getParameter("title"));
        news.setContent(request.getParameter("content"));
        news.setCreateTime(new Date());
        User user = (User) request.getSession().getAttribute("currentUser");
        if (user!=null){
            news.setUserId(user.getId());
        }

        NewsService newsService = new NewsServiceImpl();
        if (newsService.insert(news).getId() != null) {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("<script>");
            out.println("alert('发布新闻成功！');");
            out.println("location.href='" + request.getContextPath() + "/manage/news';");
            out.println("</script>");
        } else {
            request.setAttribute("errorMsg", "发布失败");
            doGet(request, response);
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/manage/news/news-add.jsp").forward(request, response);
    }
}
